package com.it.tydic.estate.module.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.it.tydic.estate.common.aop.CodeMsg;
import com.it.tydic.estate.common.aop.Result;
import com.it.tydic.estate.common.util.InstaIdGenerator;
import com.it.tydic.estate.common.util.StringUtils;
import com.it.tydic.estate.common.util.TimeUtil;
import com.it.tydic.estate.module.mapper.inner.TbCkglRkckdmxMapper;
import com.it.tydic.estate.module.mapper.inner.TbCkglRkckglMapper;
import com.it.tydic.estate.module.mapper.inner.TbCkglWpdaMapper;
import com.it.tydic.estate.module.mapper.inner.TbCkglWpkcMapper;
import com.it.tydic.estate.module.model.inner.*;
import com.it.tydic.estate.module.service.CkglService;
import com.it.tydic.estate.module.service.RkglService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import java.util.*;

@Transactional
@Service
public class CkglServiceImpl implements CkglService {

    @Autowired
    private TbCkglRkckglMapper ckglMapper;

    @Autowired
    private TbCkglRkckdmxMapper rkdmxMapper;

    @Autowired
    private TbCkglWpkcMapper wpkcMapper;

    @Autowired
    private TbCkglWpdaMapper wpdaMapper;

    /**
     * 新增修改出库单信息
     * @param ckgl
     * @return
     */
    @Override
    public Result insertOrUpdate(TbCkglRkckgl ckgl) {
        //必传项参数校验
        if(StringUtil.isEmpty(ckgl.getDjbh()) || ckgl.getFsrq()==null || StringUtil.isEmpty(ckgl.getUserId())
                || StringUtil.isEmpty(ckgl.getJsr()) || StringUtil.isEmpty(ckgl.getSzck())){
            return  Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        if(StringUtil.isEmpty(ckgl.getId())){//判断如果为空新增
            //首先新增入库单信息
            ckgl.setId(String.valueOf(new InstaIdGenerator().nextId(TimeUtil.timeGen())));
            ckgl.setZfbj("0");
            ckgl.setCreateTime(new Date());
            ckgl.setUpdateTime(new Date());
            ckgl.setShzt(0);//设置默认审核单据为未审核 0
            ckgl.setDjlb("1");//设置单据类别为 出库
            int index = ckglMapper.insert(ckgl);
            if(index==1){
                //保存入库单详情信息
                addRkdxq(ckgl);
                return Result.success(ckgl.getId());
            }else {
                return  Result.error(CodeMsg.INSERT_ERROR);
            }
        }else {
            //首先修改入库管理
            ckgl.setUpdateTime(new Date());
            int index = ckglMapper.updateByPrimaryKeySelective(ckgl);
            if(index==1){
                //修改入库单明细表
                //uodateRkdxq(ckgl);
                return Result.success();
            }else {
                return  Result.error(CodeMsg.UPDATE_ERROR);
            }
        }
    }

    /**
     * 修改入库管理详情列表
     * @param rkgl
     */
    private void uodateRkdxq(TbCkglRkckgl rkgl) {
        if(rkgl.getRkckdmxList()!=null && rkgl.getRkckdmxList().size()!=0){
            //首先恢复物品库存数量
            recoverWpkc(rkgl);
            //2.先根据入库管理ID批量删除
            Example example = new Example(TbCkglRkckdmx.class);
            example.createCriteria().andEqualTo("rkglId",rkgl.getId());
            rkdmxMapper.deleteByExample(example);
            InstaIdGenerator idGenerator = new InstaIdGenerator();
            for (TbCkglRkckdmx rkdmx : rkgl.getRkckdmxList()) {
                rkdmx.setId(String.valueOf(idGenerator.nextId(TimeUtil.timeGen())));
                rkdmx.setRkglId(rkgl.getId());
                rkdmx.setUpdateTime(new Date());
                rkdmx.setCreateTime(new Date());
                rkdmx.setCkId(rkgl.getSzck());
            }
            rkdmxMapper.insertByList(rkgl.getRkckdmxList());
            //减去物品库存表
            subWpkcInfo(rkgl.getRkckdmxList());
        }
    }
    /**
     * 恢复物品库存
     * @param rkgl
     */
    private void recoverWpkc(TbCkglRkckgl rkgl) {
        Example example = new Example(TbCkglRkckdmx.class);
        example.createCriteria().andEqualTo("rkglId",rkgl.getId());
        //查询出之前的出库物品数量
        List<TbCkglRkckdmx> rkckdMxList = rkdmxMapper.selectByExample(example);
        if(rkckdMxList.size()>0){
            Example wpkcExample = new Example(TbCkglWpkc.class);
            wpkcExample.createCriteria().andEqualTo("ckId",rkckdMxList.get(0).getCkId());
            //现有库存数量
            List<TbCkglWpkc> wpkcOld = wpkcMapper.selectByExample(wpkcExample);
            ArrayList<TbCkglWpkc> updateWpkc = new ArrayList<>();
            for (TbCkglRkckdmx wpmx : rkckdMxList) {
                for (TbCkglWpkc wpkc : wpkcOld) {
                    if(wpmx.getWpId().equals(wpkc.getWpId())){
                        wpkc.setSl(String.valueOf(Integer.parseInt(wpkc.getSl())
                                +Integer.parseInt(wpmx.getSl())));
                        updateWpkc.add(wpkc);
                    }
                }
            }
            //批量恢复物品库存
            if(updateWpkc.size()>0){
                for (TbCkglWpkc wpkc : updateWpkc) {
                    wpkcMapper.updateByPrimaryKeySelective(wpkc);
                }
            }
        }
    }
    /**
     * 添加出库单详情
     *      * @param rkgl
     */
    private void addRkdxq(TbCkglRkckgl rkgl) {
        if(rkgl.getRkckdmxList()!=null && rkgl.getRkckdmxList().size()!=0){
            InstaIdGenerator idGenerator = new InstaIdGenerator();
            for (TbCkglRkckdmx rkdmx : rkgl.getRkckdmxList()) {
                rkdmx.setId(String.valueOf(idGenerator.nextId(TimeUtil.timeGen())));
                rkdmx.setRkglId(rkgl.getId());//出库单ID
                rkdmx.setCkId(rkgl.getSzck());//仓库ID
                rkdmx.setUpdateTime(new Date());
                rkdmx.setCreateTime(new Date());
                rkdmx.setCkId(rkgl.getSzck());
            }
            rkdmxMapper.insertByList(rkgl.getRkckdmxList());
            //减少物品库存表
            subWpkcInfo(rkgl.getRkckdmxList());
        }
    }

    /**
     * 减少物品库存
     * @param rkckdmxList
     */
    private void subWpkcInfo(List<TbCkglRkckdmx> rkckdmxList) {
        //先根据仓库ID查询出本仓库的物品数据
        Example wpkcExample = new Example(TbCkglWpkc.class);
        wpkcExample.createCriteria().andEqualTo("ckId",rkckdmxList.get(0).getCkId());
        List<TbCkglWpkc> wpkcOld = wpkcMapper.selectByExample(wpkcExample);
        //然后做数据对比
        List<TbCkglWpkc> wpkcNew = new ArrayList<>();
        List<String> ids = new ArrayList<>();
        for (TbCkglRkckdmx rkckdmx : rkckdmxList) {
            for (TbCkglWpkc oldWpkc : wpkcOld) {
                //将明细单物品ID和库存数据物品ID对比
                if(rkckdmx.getWpId().equals(oldWpkc.getWpId())){
                    //如果一致的话 将数量减少
                    oldWpkc.setSl(String.valueOf(Integer.parseInt(oldWpkc.getSl())
                            -Integer.parseInt(rkckdmx.getSl())));
                    wpkcNew.add(oldWpkc);
                    ids.add(oldWpkc.getId());
                }
            }
        }
        //将最新的数量修改到wpkc数据库中
        for (TbCkglWpkc wpkc : wpkcNew) {
            wpkcMapper.updateByPrimaryKeySelective(wpkc);
        }
    }

    /**
     * 根据主键查询
     * @param id
     * @return
     */
    @Override
    public Result getById(String id) {
        if(StringUtil.isEmpty(id)){
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        TbCkglRkckgl rkgl = ckglMapper.selectByPrimaryKey(id);
        if(rkgl==null){
            return Result.error(CodeMsg.DATA_NOT_EXIST);
        }
        //根据入库管理ID查询入库单明细
        Example example = new Example(TbCkglRkckdmx.class);
        example.createCriteria().andEqualTo("rkglId",rkgl.getId());
        List<TbCkglRkckdmx> tbCkglRkdmxes = rkdmxMapper.selectByExample(example);
        rkgl.setRkckdmxList(tbCkglRkdmxes);
        return Result.success(rkgl);
    }
    /**
     * 列表页面查询
     * @param map
     * @return
     */
    @Override
    public Result pageList(Map<String,Object> map) {
        if(isNotNull(map)){//参数验证
            Map<String,Object> dataMap = new HashMap<>();
            Example example = new Example(TbCkglRkckgl.class);
            PageHelper.startPage((Integer) map.get("pageNum"),(Integer)map.get("pageSize"));
            //setExample(example,map);//添加查询条件
            map.put("djlb","1");
            Page<TbCkglRkckgl> pageList = ckglMapper.pageList(map);
            dataMap.put("data",pageList.getResult());
            dataMap.put("totle",pageList.getTotal());
            return Result.success(dataMap);
        }
        return Result.error(CodeMsg.INTER_ERROR);
    }

    /**
     * 添加列表查询条件
     * @param example
     * @param map
     */
    private void setExample(Example example, Map<String, Object> map) {
        example.setOrderByClause("UPDATE_TIME DESC");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("zfbj","0").andEqualTo("djlb","1").andEqualTo("userId",map.get("userId"));
        if(StringUtils.isNotEmpty(String.valueOf(map.get("szck")))){
            criteria.andEqualTo("szck",String.valueOf(map.get("szck")));
        }
        if(StringUtils.isNotEmpty(String.valueOf(map.get("jsr")))){
            criteria.andLike("jsr",String.valueOf(map.get("jsr")));
        }
        if(StringUtils.isNotEmpty(String.valueOf(map.get("codeId")))){//制单人
            criteria.andLike("codeId",String.valueOf(map.get("codeId")));
        }
        if(StringUtils.isNotEmpty(String.valueOf(map.get("shzt")))){
            criteria.andLike("shzt",String.valueOf(map.get("shzt")));
        }
        if(StringUtils.isNotEmpty(String.valueOf(map.get("ksrq")))){
            criteria.andGreaterThanOrEqualTo("fsrq",String.valueOf(map.get("ksrq")));
        }
        if(StringUtils.isNotEmpty(String.valueOf(map.get("jsrq")))){
            criteria.andLessThanOrEqualTo("fsrq",String.valueOf(map.get("jsrq")));
        }

    }

    /**
     * 根据ids 批量删除
     * @param ids 主键ids数组
     * @return
     */
    @Override
    public Result deleteByIds(List<String> ids) {
        if (ids.size() == 0) {
            return  Result.error(CodeMsg.INTER_ERROR,null);
        }
        TbCkglRkckgl tbCkglRkckgl = new TbCkglRkckgl();
        tbCkglRkckgl.setZfbj("1");
        Example example = new Example(TbCkglCkda.class);
        example.createCriteria().andIn("id",ids);
        int result = ckglMapper.updateByExampleSelective(tbCkglRkckgl,example);
        if (result == ids.size()) {
            return  Result.success(CodeMsg.SUCCESS);
        }
        return Result.error(CodeMsg.INTER_ERROR, null);
    }

    /**
     *验证map参数
     */
    private Boolean isNotNull(Map<String,Object> map) {
        if(StringUtil.isEmpty(String.valueOf(map.get("pageNum")) )|| StringUtil.isEmpty(String.valueOf(map.get("pageSize")))){
            return false;
        }
        return true;
    }

}
